import 'dart:async';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_demo/config/dimens.dart';
import 'package:flutter_demo/widget/ToastUtil.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:intl/intl.dart' show DateFormat;
import 'package:intl/date_symbol_data_local.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

import '../widget/ToastUtil.dart';
import '../widget/ToastUtil.dart';

class RecordView extends StatefulWidget {
  final Function onSaved;
  RecordView({@required this.onSaved});
  @override
  _RecordViewState createState() => _RecordViewState();
}

enum RecordPlayState {
  record,
  recording,
}

class _RecordViewState extends State<RecordView> {

  StreamSubscription _recorderSubscription;
  String _recorderTxt = '00:00:00';
  double _dbLevel = 0.0;
  FlutterSoundRecorder recorderModule = FlutterSoundRecorder();
  var _path = "";
  bool isRecording;
  @override
  void initState() {
    super.initState();
    init();
  }
  Future<void> _initializeExample(bool withUI) async {
    await recorderModule.setSubscriptionDuration(Duration(milliseconds: 10));
    await initializeDateFormatting();
  }

  Future<void> init() async {
    await recorderModule.openAudioSession(
        focus: AudioFocus.requestFocusAndStopOthers,
        category: SessionCategory.playAndRecord,
        mode: SessionMode.modeDefault,
        device: AudioDevice.speaker);
    isRecording = false;
    await _initializeExample(false);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Stack(
        children: [
          buildRecordText(),
          buildFunctionContainer()
        ],
      ),
    );
  }

  Widget buildRecordText() {
    return Container(
      margin: EdgeInsets.only(
          bottom: Dimens.getNavBarheight +
              Dimens.bottom_sheet_item_height +
              Dimens.dHeight46),
      width: double.infinity,
      child: InkWell(
        onTap: () async {},
        child: Center(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                    padding: EdgeInsets.only(
                        top: Dimens.dHeight2,
                        bottom: Dimens.dHeight2,
                        left: Dimens.dWidth24,
                        right: Dimens.dWidth24),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(Dimens.dWidth5),
                      color: Colors.red,
                    ),
                    child: Text(
                      _recorderTxt,
                      style: TextStyle(
                          color: Colors.white, fontSize: Dimens.font_sp30),
                      textAlign: TextAlign.center,
                    )),
                IconButton(icon: Icon(Icons.volume_up), onPressed: () {}),
              ],
            )),
      ),
    );
  }

  Widget buildFunctionContainer() {
    return Positioned(
      bottom: Dimens.dHeight29 + Dimens.bottom_sheet_item_height,
      left: Dimens.dWidth44,
      right: Dimens.dWidth44,
      child: Container(
        padding:
        EdgeInsets.only(top: Dimens.getNavBarheight + Dimens.dHeight29),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            SizedBox(),
            ///删除
            InkWell(
              //删除
              onTap: () {
                File dir = File(_path);
                dir.delete().then((value) {
                  ToastUtil.showTip('删除成功');
                  setState(() {
                    _path = '';
                    _recorderTxt = '00:00:00';
                  });
                });
              },
              child: Container(
                //删除
                  height: Dimens.dWidth90,
                  width: Dimens.dWidth90,
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(Dimens.dWidth45),
                      color: Color(0xFF91D0F1)),
                  child: Icon(
                    Icons.clear,
                    size: Dimens.dWidth45,
                    color: Colors.white,
                  )),
            ),
            //录音
            Container(
              width: Dimens.dWidth90,
              height: Dimens.dWidth90,
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(Dimens.dWidth45),
                  color: Colors.red),
              child: Center(
                child: InkWell(onTap: () {

                  if (recorderModule.isRecording) {
                    stopRecorder();
                  } else {
                    if (_path != '') {
                      return ToastUtil.showTip('您有一个录音尚未处理');
                    }
                    startRecorder();
                  }
                }, child: Icon(Icons.mic)),
              ),
            ),
            //保存
            InkWell(
              //保存
              onTap: () async {
                if (_path == '') {
                  ToastUtil.showTip('尚未有要保存的录音');
                }
                _path = '';
                _recorderTxt = '00:00:00';
                ToastUtil.showTip('保存成功');
              },
              child: Container(
                height: Dimens.dWidth90,
                width: Dimens.dWidth90,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(Dimens.dWidth45),
                    color: Color(0xFF91D0F1)),
                child: Icon(
                  Icons.save,
                  size: Dimens.dWidth45,
                  color: Colors.white,
                ),
              ),
            ),
            SizedBox()
          ],
        ),
      ),
    );
  }
  void cancelRecorderSubscriptions() {
    if (_recorderSubscription != null) {
      _recorderSubscription.cancel();
      _recorderSubscription = null;
    }
  }

  void startRecorder() async {
    try {
      if (!kIsWeb) {
        var status = await Permission.microphone.request();
        if (status != PermissionStatus.granted) {
          ToastUtil.showTip('您尚未开通权限');
        }
      }
      Directory appDirectory = await getApplicationDocumentsDirectory();
      String filePath = appDirectory.path + '/' + DateTime.now().millisecondsSinceEpoch.toString() + '.aac';

      recorderModule.startRecorder(
        toFile:filePath,
        codec: Codec.aacADTS,
      ).then((value) {
      });

      _recorderSubscription = recorderModule.onProgress.listen((e) {
        if (e != null && e.duration != null) {
          var date = DateTime.fromMillisecondsSinceEpoch(
              e.duration.inMilliseconds,
              isUtc: true);
          var txt = DateFormat('mm:ss:SS', 'en_GB').format(date);

          setState(() {
            _recorderTxt = txt.substring(0, 8);
            _dbLevel = e.decibels;
          });
        }
      });
      setState(() {
        isRecording = true;
        _path = filePath;
      });
    } catch (e){}
  }

  void stopRecorder() async {
    try {
      await recorderModule.stopRecorder();
      print('stopRecorder');
      cancelRecorderSubscriptions();
    } on Exception catch (err) {
      print('stopRecorder error: $err');
    }
    setState(() {
      isRecording = false;
    });
  }
}
